<template>
  <div class="coursesList">
    <el-switch class="showListControl" v-if="getUserIsAdmin" v-model="showAll" active-text="所有课程" inactive-text="我的课程"></el-switch>
    <div
      class="course hover_boxShadow_defaut"
      :class="{ latelyOpen: item.latelyOpen }"
      v-for="(item, index) in getCoursesData"
      :key="index"
      :style="{
        'margin-right': (index + 1) % 4 === 0 ? '0' : '20px',
      }"
      @click="handelJumpRoute(item)"
      :title="item.latelyOpen ? '最近更新' : item.name"
    >
      <!-- <div class="isContinuousPublish" v-if="item.isContinuousPublish"> -->
      <div class="continueLabel" v-if="item.isContinuousPublish">
        <span class="content">持续发布</span>
      </div>
      <!-- <img
          :src="require('@/assets/images/isContinuousPublishIcon.png')"
          title="持续发布"
        /> -->
      <!-- </div> -->
      <!-- <div class="latelyIconBox" v-if="item.latelyOpen">
        <img
          :src="require('@/assets/images/latelyIcon.png')"
          title="最近打开"
        />
      </div> -->
      <div class="addCourse" v-if="index === 0">
        <div>
          <img :src="require('@/assets/images/bigAddcourse.png')" />
        </div>
        <div class="title">新建课程</div>
      </div>
      <div class="containerBox" v-if="!item.createCourses">
        <div class="iconBox">
          <img
            v-lazy="item.iconPath"
            :title="item.iconPath ? '课程封面' : '暂无课程封面'"
          />
        </div>
        <div class="courseName">
          {{ item.name || "【缺课程名称】" }}
        </div>
        <div class="courseDesc">
          设计：{{ filterUserName(item.mainDesignerUserID) }} {{getOtherDesignerUser(item.otherDesigerUserIDList)}}
        </div>
        <div class="courseInfo">
          <div class="desc">简介：{{ item.description || "无" }}</div>
        </div>
        <div class="time">
          修改时间：{{ item.lastUpdatedTime || "【修改时间】" | filterTime }}
        </div>
      </div>
      <div class="btnBox" v-if="index !== 0">
        <div class="btn">查看详情</div>
        <div class="btn" @click.stop="deleteConfirm(item)">删除课程</div>
      </div>
    </div>
  </div>
</template>

<script>
// import { getCurriculumlist } from '@/request/courses'
import { getDesigncourselist, deleteCourse } from "@/request/designcourse";
import { Session } from "@/util/storage/session"
import { mapState } from "vuex";
import { location, currTime, renderTimeToYMD } from "@/util/tool";
export default {
  data() {
    return {
      latelyOpen: [],
      coursesData: [],
      location: location(window),
      showAll: false,
    };
  },
  computed: {
    getCoursesData() {
      var nData = this.showAll ? JSON.parse(JSON.stringify(this.designcourselist)) : JSON.parse(JSON.stringify(this.myDesigningCourses));
      nData.sort((a, b) => {
        let t_1 = new Date(a.lastUpdatedTime).getTime();
        let t_2 = new Date(b.lastUpdatedTime).getTime();
        return t_2 - t_1;
      });

      nData.map((item, index) => {
        if (index <= 6) {
          this.$set(item, "latelyOpen", true);
        }
      });
      nData.unshift({ createCourses: true });
      return nData;
    },
    ...mapState({
      userInfo: (state) => state.user.userInfo,
      userList:(state) => state.user.userList,
      myDesigningCourses: (state) => state.courses.myDesigningCourses,
      designcourselist: (state) => state.courses.designcourselist
      // myDesignCourses: (state) => state.courses.myDesignCourses
    }),
    filterUserName: () => {
      return function (val) {
        const findUser = this.userList.find(item => item.userID === val)
        return !findUser ? val : findUser.realName || findUser.nickName || findUser.email || findUser.regName;
      }
    },
    getOtherDesignerUser() {
      return function (data) {
        const otherDesigner = data?.split(",")
        if (!otherDesigner) return ""
        const list = this.userList.filter(item => {
          return otherDesigner.indexOf(`${item.userID}`) !== -1
        }).map(item => item.realName || item.nickName || item.email || item.regName)
        return list.length ? "、" + list.join("、") : ""
      }
    },
    getUserIsAdmin() {
        return this.userInfo.regName == '21003' || this.userInfo.regName == '10241' || this.userInfo.regName == '10075'
    },
  },
  filters: {
    filterTime(val) {
      const time = new Date(val);
      return renderTimeToYMD(time) + ' ' + currTime(time);
    },
    
  },
  created() {
    if (!this.userList.length) this.$store.dispatch("user/getUserList")
    this.fetchCurriculumlist();
  },
  methods: {
    // 获取可选修课程
    fetchCurriculumlist() {
      this.$store.dispatch("courses/fetchDesignCourses", {that: this})
      // getDesigncourselist().then((data) => {
      //   if (data) {
      //     data = data?.filter(
      //       (item) => item.state == "创作中" || item.state == "持续发布"
      //     );
      //     const { userID } = this.userInfo
      //     data = data?.filter(
      //       (item) => {
      //         return item.mainDesignerUserID === userID || (item.otherDesigerUserIDList && item.otherDesigerUserIDList?.indexOf(userID) !== -1)
      //       }
      //     );

      //     data.sort((a, b) => {
      //       let t_1 = new Date(a.lastUpdatedTime).getTime();
      //       let t_2 = new Date(b.lastUpdatedTime).getTime();
      //       return t_2 - t_1;
      //     });

      //     // data?.reverse() || [];
      //     data.map((item, index) => {
      //       if (index <= 6) {
      //         this.$set(item, "latelyOpen", true);
      //       }
      //     });
      //     this.coursesData = data;
      //   } else {
      //     this.$antdMessage.error({
      //       content: "获取创作中的课程失败",
      //     });
      //   }
      // });
    },
    // 跳转课程创作页面
    handelJumpRoute(item) {
      if (item.courseID) {
        this.$router.push({
          name: "Creativeourse",
          query: {
            courseID: item.courseID,
          },
          params: { id: item.courseID },
        });
      } else {
        this.$router.push({
          name: "Creativeourse",
          params: { id: 0 },
        });
      }
    },
    handelCoursesDetail(item) {
      this.$router.push({
        name: "Coursedetail",
        query: { courseId: item.courseID, currNo: item.currNo },
        // params: { id: item.courseID },
      });
    },
    deleteConfirm(item) {
      this.$confirm(
        "是否确认删除课程",
        {
          title: "提示",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
          callback: (action) => {
            if (action == 'confirm') this.handleDelete(item);
          },
        }
      );
    },
    // 删除课程
    handleDelete(item) {
      // if (!this.$route.query.courseID) {
      //   this.$antdMessage.error({
      //     content: "课程未创建，无法删除！",
      //   });
      //   return;
      // }
      // if (this.courseDetailData.isContinuousPublish) {
      //   let checkHavePubTask = this.handleCheckHavePubTask();
      //   if (checkHavePubTask) {
      //     this.$antdMessage.warning({
      //       content: "课程含有已发布的任务，无法删除课程！",
      //     });
      //     return;
      //   }
      // }
      let params = {
        courseID: Number(item.courseID),
        userID: this.userInfo.userID,
      };
      deleteCourse(params).then((res) => {
        if (res.errno === 0) {
          this.$antdMessage.success({
            content: "删除成功！",
          });
          Session.remove('/d_api/designcourse/designcourselist')
          Session.remove('/d_api/designcourse/designcourselist?state=已删除')
          this.$store.dispatch('courses/fetchDesignCourses')
          this.$store.dispatch('courses/fetchDesignDeteleCoursesList')
        } else {
          this.$antdMessage.error({
            content: res.message || res,
          });
        }
      });
    },
    // 显示所有课程
    changeShowAll() {
      this.showAll = !this.showAll
    }
  },
};
</script>

<style lang="stylus">
.coursesList {
  margin: 0 auto;
  max-width: 1200px;
  display: flex;
  justify-content: flex-start;
  flex-flow: row wrap;
  position: relative;

  .showListControl {
    position: absolute;
    top: 5px;
  }

  .course {
    cursor: pointer;
    margin-right: 36px;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-top: 25px;
    width: 285px;
    height: 340px;
    background-color: #ffffff;
    // box-shadow: 0px 8px 16px 0px rgba(79, 111, 139, 0.16);
    border-radius: 5px;
    overflow: hidden;
    transition: box-shadow 0.2s linear;

    .addCourse {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;

      .title {
        margin-top: 64px;
        font-family: PMingLiU-ExtB;
        font-size: 22px;
        color: rgba(129, 129, 129, 0.63);
      }
    }

    .containerBox {
      padding: 17px 15px 0;

      .iconBox {
        width: 255px;
        height: 146px;

        img {
          object-fit: cover;
          width: 100%;
          height: 100%;
          border-radius: 5px;
        }
      }

      .courseName {
        margin-top: 7px;
        display: inline-block;
        line-height: 27px;
        font-family: PMingLiU-ExtB;
        font-weight: bold;
        font-size: 20px;
        color: #333333;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .courseDesc {
        margin-top: 5px;
        line-height: 19px;
        font-family: PMingLiU-ExtB;
        font-size: 14px;
        color: #999999;
      }

      .courseInfo {
        margin-top: 9px;
        line-height: 19px;
        display: flex;
        font-family: PMingLiU-ExtB;
        font-size: 14px;
        color: #666666;

        .desc {
          margin: 0 10px;
          position: relative;
          // height: 57px;
          overflow: hidden;
          text-overflow: ellipsis;
          word-break: break-all;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .desc:first-child {
          margin-left: 0;
        }

        .desc:last-child {
          margin-right: 0;
        }

        .desc::after {
          position: absolute;
          content: '';
          top: 1.5px;
          right: -10px;
          height: 15px;
          width: 1px;
          background: #666666;
        }

        .desc:last-child::after {
          content: none;
        }
      }

      .time {
        margin-top: 9px;
        line-height: 19px;
        font-family: PMingLiU-ExtB;
        font-size: 14px;
        color: #666666;
      }

    }
    .btnBox {
      display: flex;
      width: 100%
      height 38px;
      line-height: 38px;
      .btn {
        cursor: pointer;
        flex: 1;
        text-align: center;
      }
      .btn:hover {
        background-color: #1c4e93
        color: #ffffff
      }
    }
  }

  // .course:hover {
  // box-shadow: 0px 8px 16px 0px rgba(79, 111, 139, 0.16);
  // }
  .isContinuousPublish {
    position: absolute;

    // right: 5px;
    // top: 5px;
    img {
      width: 20px;
      height: 25px;
    }
  }

  .latelyOpen {
    position: relative;
    background: #f9f0e1 !important;

    .latelyIconBox {
      position: absolute;
      right: 5px;
      top: 5px;

      img {
        width: 20px;
        height: 20px;
      }
    }
  }

  .continueLabel {
    top: -15px;
    right: 0px;
    width: 145px;
    height: 145px;
    position: absolute;
    overflow: hidden;

    .content {
      top: 25px;
      right: -70px;
      transform: rotate(45deg);
      display: inline-block;
      text-align: center;
      width: 200px;
      height: 40px;
      line-height: 40px;
      position: absolute;
      z-index: 2;
      color: #fff;
      overflow: hidden;
      box-shadow: 0 0 1px 1px #035386;
      background: #035386;
    }
  }
}
</style>
